package com.qiwx.pigeon.base;


import com.qiwx.pigeon.Utils.ReferenceUtil;
import com.qiwx.pigeon.Utils.RxThreadUtil;
import com.trello.rxlifecycle.LifecycleProvider;
import com.trello.rxlifecycle.android.ActivityEvent;
import com.trello.rxlifecycle.android.FragmentEvent;
import com.trello.rxlifecycle.components.support.RxFragment;

import java.lang.ref.WeakReference;

import rx.Observable;


/**
 * Base class that implements the Presenter interface and provides a base implementation for
 * attachView() and detachView(). It also handles keeping a reference to the mvpView that
 * can be accessed from the children classes by calling getMvpView().
 */
public abstract class BasePresenter<T extends IBaseView> {
    protected String TAG = this.getClass().getName();
    protected WeakReference<T> baseView;//防止内存泄漏



    public BasePresenter(WeakReference<T> from) {
        this.baseView = from;
    }
    public BasePresenter(T from) {
        this.baseView = new WeakReference<T>(from);
    }

    public void detachView() {
        if (!ReferenceUtil.checkNull(baseView)) {
            baseView.clear();
        }
    }

    /**
     * 获取view的方法
     *
     * @return 当前关联的view
     */
    public T getView() {
        if(!ReferenceUtil.checkNull(baseView)){
            return baseView.get();
        }
        return null;
    }

    protected Observable.Transformer getRxTransformer(){

        return createDefaultTransformer();
//        LifecycleProvider lifecycleProvider = getView().getLifecycleProvider();
//        if(lifecycleProvider == null){
//            return createDefaultTransformer();
//        }
//        if(lifecycleProvider instanceof RxFragment){
//            return lifecycleProvider.bindUntilEvent(FragmentEvent.DESTROY_VIEW);
//        }else{
//            return lifecycleProvider.bindUntilEvent(ActivityEvent.DESTROY);
//        }
    }

    private Observable.Transformer createDefaultTransformer(){
        return RxThreadUtil.normalSchedulers();
    }
}

